/**
 * 发送消息
 */
export function sendMessageByWs(message, request) {
	request.chat.isChating = true;
	// 初始化
	init(message, request);
	// console.log('request-before: ',request);
	chat(request);
}


/**
 * 初始化
 */
function init(message, request) {
    // 添加新的消息到消息列表中
    const chatMessages = request.chat.messages;
    chatMessages.push(uni.$u.chat.newUseMessage(message));

    request.streamMsg = "";
    request.lastRenderTimes = uni.$u.chat.curTime(); // 最后一次渲染时间
	
	var requestParams  = request.chat.requestParams;
	requestParams.user_input = message;
    request.current_request = requestParams; // 本次请求得上下文

    // request.renderTimeInterval = uni.$u.chat.getRenderTimeInterval(chatMessages.length); // 渲染时间间隔
    request.renderTimeInterval = 0; // 渲染时间间隔
    request.newMessage = uni.$u.chat.newMessage(); // 新消息
    chatMessages.push(request.newMessage);
    request.updateVuexChatList(request); // 更新缓存
    request.delayedScrollToBottom(); // 滚动消息到底部
}

function chat(request){
	// 创建 WebSocket 链接
	request.wsClient = new WebSocket("wss://gptapi.hackyin.top/api/v1/chat-stream");
	
	// 监听 WebSocket 打开
	request.wsClient.onopen = (event) => {
		request.wsClient.send(JSON.stringify(request.current_request));
	};
	
	// 监听 WebSocket 消息
	request.wsClient.onmessage = (event) => {
	    const info = JSON.parse(event.data);
		let data = info.data;
		
		if(info.event == "text_stream"){
		      if(info.message_num > 1){
		        request.chat.requestParams.history = info.history;
		        var cur_message_obj = info.history.visible;
				var cur_msg = cur_message_obj[cur_message_obj.length - 1][1];
				request.streamMsg = cur_msg;
		        chatRenderText(request);
		      }
		    }
		
		    if(info.event == "stream_end"){
				wsClose(request); // 关闭 WebSocket 链接
		    }
			
	};
	// 监听 WebSocket 消息异常
	request.wsClient.onerror = (event) => {
	    console.log('WebSocket connection closed, event: ', JSON.stringify(event));
	    wsClose(request);
	};
	// 监听 WebSocket 关闭
	request.wsClient.onclose = (event) => {
	    wsClose(request);
	};
}


/**
 * 关闭 WebSocket 链接
 */
function wsClose(request) {
    request.streamMsg = uni.$u.chat.streamCloseMsg(request.streamMsg);
    chatRenderText(request, true);
    request.newMessage.streaming = false;
	request.chat.isChating = false;
    if (request.wsClient) {
        request.wsClient.close();
        request.updateVuexChatList(request);
    }
}

/**
 * 渲染消息
 */
function chatRenderText(request, flag) {
    if (request.newMessage.streaming || flag) {
        request.newMessage.content = request.streamMsg;
        request.scrollToBottom(2);
    } else {
        sseChatClose(request);
    }
}